<template>
  <div class="page-content">
    <div class="header" style="margin-bottom: 1.5rem">
      <h3>会员权益</h3>
    </div>
    <el-form :model="searchForm" ref="searchFormRef" label-width="82px" style="padding-bottom: 1.5rem">
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="VIP名称：" prop="queryCondition">
            <el-input placeholder="请输入VIP名称" v-model="searchForm.queryCondition" clearable @blur="getData"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="车型：" prop="carModelId">
            <el-select v-model="searchForm.carModelId" placeholder="请选择车型" clearable @change="getData">
              <el-option v-for="item in carList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <div class="databox">
            <label class="el-form-item__label">创建时间：</label>
            <el-date-picker label="创建时间：" v-model="datavalue1" type="datetimerange" start-placeholder="开始日期"
              end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss"
              @change="activeTime" />
          </div>
        </el-col>
      </el-row>
    </el-form>
    <el-row>
      <el-col :xs="24" :sm="12" :lg="6" class="el-col2">
        <el-button @click="showDialog('add')" v-ripple>新增会员权益</el-button>
      </el-col>
    </el-row>

    <art-table :data="tableData" :loading="tableLoading" :currentPage="pageNum" :pageSize="pageSize" :total="pageTotal"
      @current-change="currentChange" @size-change="sizeChange">
      <template #default>
        <el-table-column label="ID" prop="id" width="100" align="center" />
        <el-table-column label="排序" prop="sort" width="100" align="center" />
        <el-table-column label="VIP名称" prop="name" align="center">
          <template #default="scope">
            <div class="bankcont_title">
              <div class="bankcont_title_text">{{ scope.row.name }}</div>
            </div>
            <div style="clear: both"></div>
            <!-- 车型 -->
            <div class="cartcont">
              <el-button v-for="type in scope.row.type" :key="type" round size="small">
                {{ type }}
              </el-button>
            </div>
            <!-- end车型 -->
          </template>
        </el-table-column>
        <el-table-column label="车型" prop="carModelId" align="center">
          <template #default="scope">
            {{
              (() => {
                const car = carList.find((e: any) => e.value == scope.row.carModelId);
                return car ? `${car.label}` : '无';
              })()
            }}
          </template>
        </el-table-column>
        <el-table-column label="科目类型" prop="categoryIds" align="center">
          <template #default="scope">
            <span v-if="scope.row.categoryIds">
              <template v-for="(id, idx) in scope.row.categoryIds.split(',')" :key="id">
                <span>{{ categoryList[id] }}</span>
                <span v-if="idx < scope.row.categoryIds.split(',').length - 1">, </span>
              </template>
            </span>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column label="售价/天数" prop="price" align="center">
          <template #default="scope"> {{ scope.row.price }}元/{{ scope.row.validity }}天 </template>
        </el-table-column>
        <el-table-column label="题库权益" align="center">
          <template #default="scope">
            {{ getQuestionGroupNames(scope.row.questionGroupId) }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="描述" prop="remark" width="400" align="center" /> -->
        <el-table-column #default="scope" label="真实模拟考场权限" width="200" align="center">
          <!-- <el-switch v-model="scope.row.isExamRoomVip" :active-value="1" :inactive-value="0"
            @click="editStatus(scope.row.id, scope.row.isExamRoomVip, 2)" /> -->
          {{ scope.row.isExamRoomVip === 0 ? '全部用户可用' : '仅限VIP会员可看' }}
        </el-table-column>
        <el-table-column label="总销量/真实销量" prop="virtualSalesVolume" align="center">
          <template #default="scope"> {{ scope.row.virtualSalesVolume + scope.row.openPeopleQuantity }}/ {{
            scope.row.openPeopleQuantity }}</template>
        </el-table-column>
        <!-- <el-table-column label="已开通人数" prop="openPeopleQuantity" width="200" align="center">
          <template #default="scope">
            <el-link target="_blank" underline="never" @click="linkmemberdetails">{{
              scope.row.openPeopleQuantity
            }}</el-link>
          </template>
        </el-table-column> -->
        <el-table-column #default="scope" label="会员卡页显示状态" width="200" align="center">
          <!-- <el-switch v-model="scope.row.isDisplay" :active-value="1" :inactive-value="0"
            @click="editStatus(scope.row.id, scope.row.isDisplay, 1)" /> -->
          {{ scope.row.isDisplay === 0 ? '不显示' : '显示' }}
        </el-table-column>
        <el-table-column #default="scope" label="启用状态" width="200" align="center">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"
            @click="editStatus(scope.row.id, scope.row.status, 1)" />
        </el-table-column>
        <el-table-column label="创建时间：" prop="createTime" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150px" align="center">
          <template #default="scope">
            <el-tooltip class="box-item" effect="dark" content="编辑" placement="top-start">
              <button-table type="edit" @click="buttonMoreClick(scope.row)" />
            </el-tooltip>
            <el-tooltip class="box-item" effect="dark" content="删除" placement="top-start">
              <button-table type="delete" @click="deleteRole(scope.row.id)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </template>
    </art-table>

    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增会员权益' : '编辑会员权益'" width="30%"
      :close-on-click-modal="false">
      <div style="height: 65vh;overflow-y: auto;padding-right: 20px;">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="130px">
          <el-form-item label="排序" prop="sort">
            <el-input v-model="form.sort" />
          </el-form-item>
          <el-form-item label="VIP名称" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="副标题" prop="title">
            <el-input v-model="form.title" />
          </el-form-item>
          <el-form-item label="使用天数" prop="validity">
            <el-input v-model="form.validity">
              <template #append>天</template>
            </el-input>
          </el-form-item>
          <el-form-item label="开通价格" prop="price">
            <el-input v-model="form.price">
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="虚拟销量" prop="virtualSalesVolume">
            <el-input v-model="form.virtualSalesVolume" />
          </el-form-item>
          <el-form-item label="车型" prop="carModelId">
            <el-select v-model="form.carModelId" @change="carChange" clearable>
              <el-option v-for="item in carList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="科目类型" prop="categoryIds">
            <el-select v-model="form.categoryIds" @change="categoryIdsChange" clearable multiple>
              <el-option value="1" label="科目一" />
              <el-option value="2" label="科目二" />
              <el-option value="3" label="科目三" />
              <el-option value="4" label="科目四" />
              <el-option value="5" label="注销恢复" />
              <el-option value="6" label="满分学习" />
              <el-option value="7" label="三力测试" />
            </el-select>
          </el-form-item>
          <el-form-item label="题库类型" prop="questionGroupId">
            <el-cascader v-if="isDataLoaded" :key="cascaderKey" ref="addressInfo" v-model="questionList" :props="{
              label: 'name',
              value: 'id',
              multiple: true,
              emitPath: false
            }" :options="types_one" clearable @change="handleChange" placeholder="请选择题库类型"
              style="width: 100%"></el-cascader>
          </el-form-item>
          <!-- 全部用户可用 仅会员VIP可用 -->
          <el-form-item label="真实模拟考场权限" prop="isExamRoomVip">
            <!-- <el-switch v-model="form.isExamRoomVip" :active-value="1" :inactive-value="0" /> -->
            <el-radio-group v-model="form.isExamRoomVip">
              <el-radio value="0">全部用户可用</el-radio>
              <el-radio value="1">仅限VIP会员可看</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="会员卡页显示状态" prop="isDisplay">
            <!-- <el-switch v-model="form.isDisplay" :active-value="1" :inactive-value="0" /> -->
            <el-radio-group v-model="form.isDisplay">
              <el-radio value="0">不显示</el-radio>
              <el-radio value="1">显示</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="主图" prop="backImg">
            <el-input v-model="form.backImg" style="display: none"></el-input>
            <div class="avatar-uploader" @click="openImageDialog('bgImg')">
              <el-image v-if="bgImg" :src="bgImg" class="avatar" fit="contain"></el-image>
              <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
                  <Plus />
                </el-icon></i>
              <div v-if="bgImg" class="mask">替换</div>
              <el-icon v-if="bgImg" class="del-image" :size="20" @click.stop="handleDelImg('bgImg')">
                <CircleCloseFilled />
              </el-icon>
            </div>
          </el-form-item>
          <el-form-item label="详情图" prop="detailsImg">
            <el-input v-model="form.detailsImg" style="display: none"></el-input>
            <div class="avatar-uploader" @click="openImageDialog('infoImg')">
              <el-image v-if="infoImg" :src="infoImg" class="avatar" fit="contain"></el-image>
              <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
                  <Plus />
                </el-icon></i>
              <div v-if="infoImg" class="mask">替换</div>
              <el-icon v-if="infoImg" class="del-image" :size="20" @click.stop="handleDelImg('infoImg')">
                <CircleCloseFilled />
              </el-icon>
            </div>
          </el-form-item>
          <!-- <el-form-item label="描述" prop="remark">
            <el-input type="textarea" :rows="6" v-model="form.remark" />
          </el-form-item> -->
          <el-form-item label="启用状态" prop="status">
            <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit(formRef)">提交</el-button>
        </div>
      </template>
    </el-dialog>
    <image-selected-dialog v-if="showImageChooseDialog" :single-type="selectImageSingle"
      :show-image-choose-dialog="showImageChooseDialog" @close-dialog="handleCloseImageDialog"
      :operationType="false"></image-selected-dialog>
  </div>
</template>

<script setup lang="ts">
import { useMenuStore } from '@/store/modules/menu'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { formatMenuTitle } from '@/router/utils/utils'
import { useRouter } from 'vue-router'
import type { UploadFile } from 'element-plus'
import { nextTick } from 'vue'
import {
  editVip,
  addVip,
  vipEquity,
  questionType,
  cardsType,
  delVip
} from '@/api/userStudentsApi'
import { useUserStore } from '@/store/modules/user'
import ImageSelectedDialog from '@/views/decoration/diyComponents/ImageSelectedDialog.vue'
import { fromPairs } from 'lodash'

const router = useRouter() // 使用useRouter获取路由实例
let server = `${import.meta.env.VITE_API_URL}files`
const userStore = useUserStore()
let { accessToken } = userStore
const headers = { Authorization: 'Bearer ' + accessToken }

const dialogVisible = ref(false)
const permissionDialog = ref(false)
const menuList = computed(() => useMenuStore().getMenuList)
const disabled_banner = ref(false)
const categoryList: any = {
  '1': '科目一',
  '2': '科目二',
  '3': '科目三',
  '4': '科目四',
  '5': '注销恢复',
  '6': '满分学习',
  '7': '三力测试',
}

interface CarItem {
  value: string | number
  label: string,
  tag: string
}
const carList = ref<CarItem[]>([])
const checked1 = ref(true)
const checked2 = ref(false)
const checked3 = ref(false)
interface QuestionTopItem { id: string | number; name: string }
const types_one = ref<QuestionTopItem[]>([])
// 全局题库类型映射，用于表格显示
const globalQuestionTypes = ref<Record<string | number, string>>({})

const formRef = ref<FormInstance>()

const validateQuestionGroupId = (rule: any, value: any, callback: any) => {
  if (!value || !Array.isArray(value) || value.length === 0) {
    callback(new Error('请选择题库类型'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入活动名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  des: [{ required: true, message: '请输入分类描述', trigger: 'blur' }],
  title: [{ required: true, message: '请输入副标题', trigger: 'blur' }],
  validity: [{ required: true, message: '请输入使用天数', trigger: 'blur' }],
  price: [{ required: true, message: '请输入开通价格', trigger: 'blur' }],
  carModelId: [{ required: true, message: '请选择车型', trigger: 'change' }],
  categoryIds: [{ required: true, message: '请选择科目类型', trigger: 'change' }],
  // 用自定义校验替换原有题库类型校验
  questionGroupId: [{ required: true, validator: validateQuestionGroupId, trigger: 'change' }],
})

// 题库类型（仅一级ID数组）
const questionList = ref<any[]>([])
const isDataLoaded = ref(false)
const cascaderKey = ref(0)

const getRandomVirtualSalesVolume = () => String(Math.floor(Math.random() * 151) + 50)

interface formInterface {
  id: number
  name: string
  status: number
  sort: string
  title: string
  validity: string
  price: string
  virtualSalesVolume: string
  carModelId: string
  questionGroupId: string[]
  backImg: string
  detailsImg: string
  remark: string
  isExamRoomVip: string
  isDisplay: string
  categoryIds: string[]
}
const form: any = reactive<formInterface>({
  id: 0,
  name: '',
  status: 1,
  sort: '1',
  title: '',
  validity: '',
  price: '',
  virtualSalesVolume: '',
  carModelId: '',
  questionGroupId: [],
  backImg: '',
  detailsImg: '',
  remark: '',
  isExamRoomVip: '1',
  isDisplay: '1',
  categoryIds: []
})

const showImageChooseDialog = ref(false)
const selectImageSingle = ref(true)
const handleCloseImageDialog = (value: any) => {
  if (value && value.fileUrl) {
    if (currentImageType.value === 'bgImg') {
      bgImg.value = value.fileUrl
    } else {
      infoImg.value = value.fileUrl
    }
  }
  showImageChooseDialog.value = false
}

const currentImageType = ref('cardFrontImg')
const openImageDialog = (type: string) => {
  currentImageType.value = type
  showImageChooseDialog.value = true
}

const handleDelImg = (e: string) => {
  if (e === 'bgImg') {
    bgImg.value = ''
  } else {
    infoImg.value = ''
  }
}


const tableData = ref([])

const dialogType = ref('add')


const showDialog = async (type: string, row?: any) => {
  dialogVisible.value = true
  dialogType.value = type
  if (type === 'edit' && row) {
    form.id = row.id
    form.name = row.name
    form.title = row.title
    form.validity = row.validity
    form.price = row.price
    form.virtualSalesVolume = row.virtualSalesVolume
    form.carModelId = row.carModelId
    bgImg.value = row.backImg
    infoImg.value = row.detailsImg
    form.status = row.status
    form.remark = row.remark
    form.isExamRoomVip = String(row.isExamRoomVip)
    form.isDisplay = String(row.isDisplay)
    form.categoryIds = row.categoryIds.split(',')

    await nextTick()
    await getTreeData(row)
  } else {
    form.id = 0
    form.name = ''
    form.title = ''
    form.validity = ''
    form.price = ''
    form.virtualSalesVolume = getRandomVirtualSalesVolume()
    form.carModelId = ''
    bgImg.value = ''
    infoImg.value = ''
    form.status = 1
    form.isExamRoomVip = '1'
    form.isDisplay = '1'
    form.remark = ''
    form.questionGroupId = ''
    form.categoryIds = []
    questionList.value = []
    types_one.value = []
    isDataLoaded.value = true
  }
}

const buttonMoreClick = (row: any) => {
  showDialog('edit', row)
}

const defaultProps = {
  children: 'children',
  label: (data: any) => formatMenuTitle(data.meta?.title) || ''
}

const deleteRole = (id: string) => {
  ElMessageBox.confirm('确定删除该VIP权益吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(async () => {
    const res = await delVip(id)
    if (res.code === '00000') {
      ElMessage.success('删除成功')
      getData()
    }
  })
}
const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  form.questionGroupId = questionList.value

  await formEl.validate(async (valid) => {
    if (valid) {
      let res
      const message = dialogType.value === 'add' ? '新增成功' : '修改成功'
      form.backImg = bgImg.value
      form.detailsImg = infoImg.value
      form.categoryIds = form.categoryIds.join(',')
      const { id, ...formParams } = form
      const flatIds = (questionList.value || []).join(',')
      if (dialogType.value === 'add') {
        res = await addVip(
          {
            ...filterEmptyValues({
              ...formParams,
              questionGroupId: flatIds
            }),
            backImg: form.backImg,
            detailsImg: form.detailsImg
          }
        )
      } else {
        form.backImg = bgImg.value
        form.detailsImg = infoImg.value
        res = await editVip(
          {
            ...filterEmptyValues({
              ...form,
              questionGroupId: flatIds
            }),
            backImg: form.backImg,
            detailsImg: form.detailsImg
          }
        )
      }
      if (res.code === '00000') {
        ElMessage.success(message)
        dialogVisible.value = false
        getData()
      }
    }
  })
}
const editStatus = async (id: any, status: number, type: number) => {
  const payload: Record<string, any> = { id }
  if (type === 1) {
    payload.status = status
  } else {
    payload.isExamRoomVip = status
  }
  try {
    await editVip(payload)
  } catch (error) {
  } finally {
    getData()
  }
}
const formatDate = (date: string) => {
  return new Date(date)
    .toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
    .replace(/\//g, '-')
}
const search = () => {
  getData()
}
const columns = reactive([
  { name: '用户信息', show: true },
  { name: '手机号', show: true },
  { name: '性别', show: true },
  { name: '来源', show: true },
  { name: '状态', show: true },
  { name: '创建日期', show: true }
])
const datavalue1 = ref('') //创建时间：
const searchForm = reactive({
  queryCondition: '',
  phone: '',
  id: '',
  account: '',
  sex: '',
  userleavel: '',
  conttype_one: '',
  carModelId: '',
  queryStartTime: '',
  queryEndTime: ''
})
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
const searchFormRef = ref<FormInstance>()
const changeColumn = (list: any) => {
  columns.values = list
}
const linkmemberdetails = function () {
  // setTimeout(() => {
  //   router.push('/member/user_quanyi_details')
  // }, 0)
}

const bgImg = ref('')
const infoImg = ref('')
const tableLoading = ref(false)
const pageNum = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
const filterEmptyValues = (obj: any) => {
  const result: any = {}
  for (const key in obj) {
    if (obj[key] !== '' && obj[key] !== null && obj[key] !== undefined) {
      result[key] = obj[key]
    }
  }
  return result
}
async function getData() {
  try {
    tableLoading.value = true
    const params = filterEmptyValues(searchForm)
    const { code, data } = await vipEquity({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      queryIsVip: 1,
      ...params
    })
    if (code === '00000' && data) {
      tableData.value = data.list
      pageTotal.value = data.total

      // 为每一行加载对应的题库类型数据
      await loadQuestionTypesForTable()
    }
  } catch (e) {
  } finally {
    tableLoading.value = false
  }
}

// 为表格数据加载题库类型信息
const loadQuestionTypesForTable = async () => {
  if (!tableData.value.length) return

  // 获取所有唯一的车型和科目类型组合，确保两者都存在
  const uniqueCombinations = new Set<string>()
  tableData.value.forEach((row: any) => {
    if (row.carModelId && row.categoryIds && row.carModelId !== '' && row.categoryIds !== '') {
      uniqueCombinations.add(`${row.carModelId}-${row.categoryIds}`)
    }
  })

  // 为每个组合加载题库类型数据
  for (const combination of uniqueCombinations) {
    const [carId, categoryIds] = combination.split('-')
    // 确保carId和categoryIds都不为空
    if (carId && categoryIds) {
      try {
        const res = await questionType({ carId, categoryIds })
        if (res.code === '00000' && res.data) {
          const questionTypes = Array.isArray(res.data) ? res.data.map((n: any) => ({ id: n.id, name: n.name })) : []
          // 将题库类型数据存储到全局映射中
          questionTypes.forEach(qt => {
            if (!globalQuestionTypes.value[qt.id]) {
              globalQuestionTypes.value[qt.id] = qt.name
            }
          })
        }
      } catch (error) {
        console.error('加载题库类型失败:', error)
      }
    }
  }
}

const currentChange = (val: number) => {
  pageNum.value = val
  getData()
}

const sizeChange = (val: number) => {
  pageSize.value = val
  pageNum.value = 1
  getData()
}

const carChange = async (e: any) => {
  form.carModelId = e
  // 只有当车型和科目类型都选择了才调用接口
  if (e && form.categoryIds && form.categoryIds.length > 0) {
    let params = {
      carId: e,
      categoryIds: form.categoryIds.join(',')
    }
    const res = await questionType(filterEmptyValues(params))
    types_one.value = Array.isArray(res.data) ? res.data.map((n: any) => ({ id: n.id, name: n.name })) : []
  } else {
    // 如果条件不满足，清空题库类型数据
    types_one.value = []
    questionList.value = []
  }
}

const categoryIdsChange = async (e: any) => {
  form.categoryIds = e
  // 只有当车型和科目类型都选择了才调用接口
  if (form.carModelId && e && e.length > 0) {
    let params = {
      carId: form.carModelId,
      categoryIds: e.join(',')
    }
    const res = await questionType(filterEmptyValues(params))
    types_one.value = Array.isArray(res.data) ? res.data.map((n: any) => ({ id: n.id, name: n.name })) : []
  } else {
    // 如果条件不满足，清空题库类型数据
    types_one.value = []
    questionList.value = []
  }
}

const getTreeData = async (item: any) => {
  try {
    isDataLoaded.value = false

    // 只有当车型和科目类型都存在时才调用接口
    if (item.carModelId && item.categoryIds && item.carModelId !== '' && item.categoryIds !== '') {
      const res = await questionType({ carId: item.carModelId, categoryIds: item.categoryIds })
      if (res.code === '00000' && res.data) {
        types_one.value = Array.isArray(res.data) ? res.data.map((n: any) => ({ id: n.id, name: n.name })) : []
      } else {
        types_one.value = []
      }
    } else {
      types_one.value = []
    }

    await nextTick()
    let questionData = item.questionGroupId ? item.questionGroupId.split(',') : []
    questionList.value = questionData
    cascaderKey.value += 1
    await nextTick()
    setTimeout(() => {
      isDataLoaded.value = true
    }, 100)
  } catch (error) {
    console.error('getTreeData 错误:', error)
    types_one.value = []
    questionList.value = []
    isDataLoaded.value = true
  }
}

const getCardtype = async () => {
  const res = await cardsType()
  carList.value = res.data
}
const Refresh = () => {
  getData()
}
const addressInfo = ref()
const handleChange = (val: any) => {
  if (formRef.value) {
    form.questionGroupId = questionList.value
    formRef.value.validateField('questionGroupId')
  }
}

const simpleFindPath = (tree: any[], targetId: string | number): number[] | null => {
  for (const node of tree) {
    if (node.id == targetId) {
      return [node.id]
    }
  }
  return null
}

const activeTime = (e: any) => {
  if (e) {
    searchForm.queryStartTime = formatDate(e[0])
    searchForm.queryEndTime = formatDate(e[1])
  } else {
    searchForm.queryStartTime = ''
    searchForm.queryEndTime = ''
  }
  getData()
}

// 根据questionGroupId查找对应的名称
const getQuestionGroupNames = (questionGroupIds: string) => {
  if (!questionGroupIds) {
    return '无'
  }

  const ids = questionGroupIds.split(',')
  const names = ids.map(id => {
    // 优先从全局映射中查找
    if (globalQuestionTypes.value[id]) {
      return globalQuestionTypes.value[id]
    }
    // 如果全局映射中没有，再从types_one中查找
    const item = types_one.value.find(item => item.id == id)
    return item ? item.name : `ID:${id}`
  })

  return names.join(', ')
}

onMounted(() => {
  getData()
  getCardtype()
})
</script>

<style lang="scss" scoped>
.tag-group {
  margin-top: 0.5rem;
}

.grouptag {
  margin-right: 0.5rem;
}



.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;

  .mask {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 24px;
    background-color: rgba(0, 0, 0, 0.6);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
    color: #fff;
    font-size: 12px;
  }

  .del-image {
    display: none;
    position: absolute;
    top: 0;
    right: 0;
    cursor: pointer;
    color: #8c939d;
  }

  &:hover .mask {
    opacity: 1;
  }

  &:hover .del-image {
    display: block;
  }
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 150px;
  height: 150px;
  display: block;
}
</style>
